package http

import (
	"flare-admin/ecode"
	"github.com/gin-gonic/gin"
	"net/http"
)

type genericResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// HandlerFuncWithError 返回值中的data需要保证是json格式
type HandlerFuncWithError func(ctx *gin.Context) (data any, err error)

// Wrapper 将HandlerFuncWithError转换为gin.HandlerFunc
func Wrapper(handlerFunc HandlerFuncWithError) func(c *gin.Context) {
	return func(c *gin.Context) {
		data, err := handlerFunc(c)
		if err != nil {
			if ecode.IsBizError(err) {
				c.JSON(http.StatusOK, genericResponse{
					Code:    err.(*ecode.BizError).Code,
					Message: err.Error(),
					Data:    data,
				})

			} else {
				c.JSON(http.StatusOK, genericResponse{
					Code:    ecode.ErrUnknownError.Code,
					Message: ecode.ErrUnknownError.Error(),
					Data:    data,
				})
			}
		} else {
			c.JSON(http.StatusOK, genericResponse{
				Code:    0,
				Message: "success",
				Data:    data,
			})
		}
	}
}
